package com.wms.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.bean.User;
import com.wms.config.Result;
import com.wms.service.RedisService;
import com.wms.service.UserService;
import com.wms.util.DeCodeUtil;
import com.wms.util.JWTUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;

    @GetMapping("list")
    public Result list() {
        List<User> list = userService.list();
        return Result.success(list);
    }

    @PostMapping("add")
    public Result add(@RequestBody User user) {

//        // 密码加密处理
//        String encryptedPassword = DeCodeUtil.decode(user.getUpassword());
//        user.setUpassword(encryptedPassword);
        user.setUpassword("123456"); // 默认密码

        userService.save(user);
        User user1 = userService.getById(user.getUid());
        return Result.success("保存成功", user1);
    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        userService.removeById(id);
        return Result.success("删除成功", null);
    }

    @PutMapping("update")
    public Result update(@RequestBody User user) {
//        // 密码加密处理
//        String encryptedPassword = DeCodeUtil.decode(user.getUpassword());
//        user.setUpassword(encryptedPassword);

        userService.updateById(user);
        User user1 = userService.getById(user.getUid());
        return Result.success("更新成功", user1);
    }

    @PostMapping("login")
    public Result login(HttpServletRequest request,User user, @RequestParam("captcha") String captcha,@RequestParam("captchakey")String captchakey ) {
        String captchacheck=checkCaptcha(captchakey,captcha);
        if(!captchacheck.equals("success")){
            return Result.fail(402,captchacheck);
        }
        User user_data = userService.selectByno(user.getUno());
        // 如果有信息，对比密码是否正确
        if (user_data != null) {
            // 加密前端传入的数据和数据库密码进行比较
            String encryptedPassword = DeCodeUtil.decode(user.getUpassword());
            boolean check = encryptedPassword.equals(DeCodeUtil.decode(user_data.getUpassword()));
            if (check) {
                // 对比正确登录成功，签发token
                String token = JWTUtil.getToken();

                // 创建返回数据（添加用户角色信息）
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("urole", user_data.getUrole()); // 添加权限ID
                data.put("uname", user_data.getUname());
                data.put("ustatus", user_data.getUstatus());

                return Result.success("登陆成功", data);
            }
        }
        return Result.fail(401, "认证失败");
    }

    private String checkCaptcha(String captchakey, String captchaCode ) {
        if(captchakey==null){
            return "请求参数异常";
        }
        String code=(String)redisService.get(captchakey);
        if(code==null){
            return "验证码已过期";
        }
        if(captchaCode.equalsIgnoreCase(code)) {//忽略大小写
            return "success";
        }
        return "验证失败";
    }


    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        IPage<User> result;

        if (searchtext == null || searchtext.isEmpty()) {
            result = userService.page(page);
        } else {
            QueryWrapper<User> wrapper = new QueryWrapper<User>();
            wrapper.like("uname", searchtext)
                    .or().like("uno", searchtext)
                    .or().like("uemail", searchtext)
                    .or().like("uphone", searchtext);

            result = userService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }
}